package com.sjtu.rental.services;

import java.util.List;

import org.apache.commons.validator.GenericValidator;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sjtu.rental.entity.UserInfo;
import com.sjtu.rental.exception.RegisterException;

@Service
public class UserService {

	@Autowired
	private GenericDao genericDao;

	@Transactional
	public UserInfo login(UserInfo user) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfo.class);
		criteria.add(Restrictions.eq("uiPassword", user.getUiPassword()));
		criteria.add(Restrictions.or(Restrictions.eq("uiState", 0),
				Restrictions.eq("uiState", 1)));
		if (GenericValidator.isBlankOrNull(user.getUiEmail())) {
			criteria.add(Restrictions.eq("uiUsername", user.getUiUsername()));
		} else {
			criteria.add(Restrictions.eq("uiEmail", user.getUiEmail()));
		}
		List<?> list = genericDao.getHibernateTemplate().findByCriteria(
				criteria);
		return (UserInfo) (list.isEmpty() ? null : list.get(0));
	}

	@Transactional
	public void saveOrUpdate(UserInfo user) {
		checkUser(user);
		genericDao.getHibernateTemplate().saveOrUpdate(user);
	}

	@Transactional
	public void checkUser(UserInfo user) {
		DetachedCriteria c = DetachedCriteria.forClass(UserInfo.class);
		c.add(Restrictions.eq("uiUsernameType", 1)).add(
				Restrictions.eq("uiUsername", user.getUiUsername())).add(
				Restrictions.eq("uiState", 0));
		if (user.getUiId() != null) {
			c.add(Restrictions.not(Restrictions.idEq(user.getUiId())));
		}
		int num = genericDao.getHibernateTemplate().findByCriteria(c).size();
		if (num > 0) {
			throw new RegisterException("user.uiUsername",
					"register.username.repeat");
		}
		if (!GenericValidator.isBlankOrNull(user.getUiEmail())) {
			DetachedCriteria c2 = DetachedCriteria.forClass(UserInfo.class)
					.add(Restrictions.eq("uiEmail", user.getUiEmail()));
			if (user.getUiId() != null) {
				c2.add(Restrictions.not(Restrictions.idEq(user.getUiId())));
			}
			num = genericDao.getHibernateTemplate().findByCriteria(c2).size();
			if (num > 0) {
				throw new RegisterException("user.uiPassword",
						"register.email.repeat");
			}
		}
	}

	@Transactional
	public UserInfo getUserById(Long id) {
		return genericDao.getHibernateTemplate().get(UserInfo.class, id);
	}
}
